@echo off
setlocal enabledelayedexpansion

title stb_truetype MinGW 构建脚本
color 0A

echo ==================================================
echo      🛠️  stb_truetype 自动构建脚本 (MinGW)
echo ==================================================
echo.

REM ========== 配置 ==========
set "MINGW_PREFIX=x86_64-w64-mingw32"
set "STB_HEADER=stb_truetype.h"
set "IMPL_FILE=stb_truetype_impl.c"
set "OUTPUT_DIR=dist"
REM ===========================

REM 检查 stb_truetype.h 是否存在
if not exist "%STB_HEADER%" (
    echo ❌ 错误：找不到 %STB_HEADER%
    echo 💡 请从 https://github.com/nothings/stb/raw/master/stb_truetype.h 下载
    pause
    exit /b 1
)

REM 自动生成 stb_truetype_impl.c
if not exist "%IMPL_FILE%" (
    echo 📝 生成 %IMPL_FILE%...
    (
        echo #define STB_TRUETYPE_IMPLEMENTATION
        echo #include "%STB_HEADER%"
    ) > "%IMPL_FILE%"
)

REM 创建输出目录
if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%"

REM 检查 MinGW 是否可用
echo 🔍 检查 MinGW 编译器...
%MINGW_PREFIX%-gcc --version >nul 2>&1
if errorlevel 1 (
    echo ❌ 未找到 %MINGW_PREFIX%-gcc
    echo 💡 请安装 MSYS2 并运行：pacman -S mingw-w64-x86_64-gcc
    echo 💡 并确保 C:\msys64\mingw64\bin 已加入系统 PATH
    pause
    exit /b 1
)
echo ✅ MinGW 编译器已找到

REM 编译静态库
echo.
echo 📦 编译静态库: libstb_truetype.a
%MINGW_PREFIX%-gcc -c %IMPL_FILE% -o stb_truetype.o -O2
ar rcs "%OUTPUT_DIR%/libstb_truetype.a" stb_truetype.o
del stb_truetype.o

REM 编译动态库（关键：用引号包裹含逗号的参数）
echo.
echo 📦 编译动态库: stb_truetype.dll
%MINGW_PREFIX%-gcc -shared -O2 -o "%OUTPUT_DIR%/stb_truetype.dll" %IMPL_FILE% "-Wl,--out-implib,%OUTPUT_DIR%/libstb_truetype.dll.a"

REM 拷贝头文件
copy /Y "%STB_HEADER%" "%OUTPUT_DIR%\" >nul

REM 生成使用说明
(
    echo stb_truetype 库已生成！
    echo.
    echo 📁 输出目录: .\%OUTPUT_DIR%
    echo.
    echo 📦 静态库: libstb_truetype.a
    echo 📦 动态库: stb_truetype.dll + libstb_truetype.dll.a
    echo.
    echo 📌 使用方法:
    echo.
    echo // C 代码
    echo #include "stb_truetype.h"
    echo.
    echo // 链接静态库:
    echo %MINGW_PREFIX%-gcc main.c -I./%OUTPUT_DIR% -L./%OUTPUT_DIR% -l:libstb_truetype.a -o app.exe
    echo.
    echo // 链接动态库:
    echo %MINGW_PREFIX%-gcc main.c -I./%OUTPUT_DIR% -L./%OUTPUT_DIR% -l:libstb_truetype.dll.a -o app.exe
    echo.
    echo ⚠️ 运行时请确保 stb_truetype.dll 与可执行文件在同一目录。
) > "%OUTPUT_DIR%\README.txt"

echo.
echo 🎉 构建成功！文件已生成在 .\%OUTPUT_DIR%
echo.
pause